package com.server.llh.llhserverwork.activity.work;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.LlhBaseActivity;
import com.server.llh.llhserverwork.adapter.HealthTaskAdapter;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.SerTransWapBean;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.view.widget.JudgeDate;
import com.server.llh.llhserverwork.view.widget.ScreenInfo;
import com.server.llh.llhserverwork.view.widget.WheelMain;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ZTF on 2017-06-06.
 */

public class HealthFinishActivity extends LlhBaseActivity {
    public static final String TAG="HealthFinish";
    @BindView(R.id.startTime)
    TextView startTime;
    @BindView(R.id.stopTime)
    TextView stopTime;
    @BindView(R.id.queryServer)
    TextView queryServer;
    @BindView(R.id.timeView)
    LinearLayout timeView;
    @BindView(R.id.health_lv)
    ListView healthLv;
    SwipeRefreshLayout refehsLayout;
    String userId,  transStatus;
    @BindView(R.id.swipe_container)
    SwipeRefreshLayout swipeContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        timeView.setVisibility(View.VISIBLE);
        setTimeView(startTime);
        setTimeView(stopTime);
        userId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID,
                getApplicationContext());
        timeView.setVisibility(View.VISIBLE);
        refehsLayout = (SwipeRefreshLayout) this.findViewById(R.id.swipe_container);
        Intent intent = getIntent();
        if (intent != null) {
            transStatus = intent.getStringExtra("transStatus");
        }
        final String startTimeStr = startTime.getText().toString();
        final String stopTimeStr = stopTime.getText().toString();
        refehsLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getServerTask(userId, transStatus, startTimeStr,
                        stopTimeStr);
            }
        });
        getServerTask(userId, transStatus, startTimeStr, stopTimeStr);

    }
    List<SerTransWapBean> listData=new ArrayList<>();
    private void getServerTask(String userId, String transStatus, String startTimeStr, String stopTimeStr) {
        try {
            try {
            JSONObject json = new JSONObject();
            json.put("waitersId", userId);
            json.put("transStatus", transStatus);
            json.put("startDateStr", startTimeStr);
            json.put("endDateStr", stopTimeStr);
            LRequest lRequest = new LRequest();
            lRequest.addParam("searchTaskForWaitersForApp", URLEncoder.encode(json.toString(), "UTF-8"));
            lRequest.setUri(ServerPort.SEARCH_TASK_JSON);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
                }
                @Override
                public void onNext(String responseBean, String code) {
                    if (responseBean != null) {
                        Log.d(TAG,"responseBean=="+responseBean);
                        listData = new Gson().fromJson(responseBean,
                                new TypeToken<List<SerTransWapBean>>() {
                                }.getType());
                        HealthTaskAdapter adapter = new  HealthTaskAdapter(
                                getApplicationContext(), listData);
                        healthLv.setAdapter(adapter);
                    }
                }
            });
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
      } catch (JSONException e) {
        e.printStackTrace();
    }
    }
    @Override
    public void showProgress() {
        try{
            showProgress(HealthFinishActivity.this);
        }catch (Exception e){

        }
    }
    @Override
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }
    @Override
    public void hideProgress() {
        try {
            closeProgress();
        }catch (Exception E){
        }
    }
    @Override
    protected int getlayout() {
        return R.layout.activity_health_task;
    }
    @Override
    protected void initView() { }

    @Override
    protected void doBasess() {

    }
    @OnClick({R.id.startTime, R.id.stopTime,R.id.queryServer})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.startTime:
                showTime(startTime);
                break;
            case R.id.stopTime:
                showTime(stopTime);
                break;
            case R.id.queryServer:
                final String startTimeStr = startTime.getText().toString();
                final String stopTimeStr = stopTime.getText().toString();
                getServerTask(userId, transStatus, startTimeStr, stopTimeStr);
                break;
        }
    }

    private String monthStr, dayStr;
    public void setTimeView(final TextView view) {
        Calendar calendar = Calendar.getInstance();
        int monthInt = calendar.get(Calendar.MONTH) + 1;
        int dayInt = calendar.get(Calendar.DAY_OF_MONTH);
        if (monthInt < 10) {
            monthStr = String.valueOf("0" + monthInt);
        } else {
            monthStr = String.valueOf(monthInt);
        }
        if (dayInt < 10) {
            dayStr = String.valueOf("0" + dayInt);
        } else {
            dayStr = String.valueOf(dayInt);
        }
        view.setText(calendar.get(Calendar.YEAR) + "-" + (monthStr) + "-"
                + dayStr + "");
    }


    WheelMain wheelMain;
    @SuppressLint("SimpleDateFormat")
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    public void showTime(final TextView view) {
        LayoutInflater inflater = LayoutInflater
                .from(HealthFinishActivity.this);
        final View timepickerview = inflater.inflate(R.layout.timepicker, null);
        ScreenInfo screenInfo = new ScreenInfo(HealthFinishActivity.this);
        wheelMain = new WheelMain(timepickerview);
        wheelMain.screenheight = screenInfo.getHeight();
        String time = view.getText().toString();
        Calendar calendar = Calendar.getInstance();
        if (JudgeDate.isDate(time, "yyyy-MM-dd")) {
            try {
                calendar.setTime(dateFormat.parse(time));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        wheelMain.initDateTimePicker(year, month, day);
        new AlertDialog.Builder(HealthFinishActivity.this).setTitle("选择时间")
                .setView(timepickerview)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        view.setText(wheelMain.getTime());
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();

    }


}
